package com.usian.service.impl;

import com.usian.config.RedisClient;
import com.usian.mapper.LocalMessageMapper;
import com.usian.mapper.TbOrderItemMapper;
import com.usian.mapper.TbOrderMapper;
import com.usian.mapper.TbOrderShippingMapper;
import com.usian.mq.MQSender;
import com.usian.pojo.*;
import com.usian.service.OrderService;
import com.usian.utils.JsonUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private TbOrderMapper tbOrderMapper;

    @Autowired
    private TbOrderItemMapper tbOrderItemMapper;

    @Autowired
    private TbOrderShippingMapper tbOrderShippingMapper;

    @Autowired
    private LocalMessageMapper localMessageMapper;

    @Autowired
    private AmqpTemplate  amqpTemplate;

    @Autowired
    private MQSender mqSender;

    @Override
    public long insertOrder(OrderInfo orderInfo) {

        //生成orderId
        long orderId = redisClient.incr("ORDER_ID_KEY", 1L);

        //解析  orderInfo
        TbOrder tbOrder = orderInfo.getTbOrder();
        TbOrderShipping tbOrderShipping = orderInfo.getTbOrderShipping();
        List<TbOrderItem> tbOrderItemList =
                JsonUtils.jsonToList(orderInfo.getOrderItem(), TbOrderItem.class);

        //入库  tbOrder
        tbOrder.setOrderId(String.valueOf(orderId));
        tbOrder.setStatus(1);
        tbOrder.setCreateTime(new Date());
        tbOrder.setUpdateTime(new Date());
        tbOrderMapper.insertSelective(tbOrder);

        //tborderItem
        for (int i = 0; i < tbOrderItemList.size(); i++) {
            Long oderItemId = redisClient.incr("ORDER_ITEM_ID_KEY", 1L);
            TbOrderItem tbOrderItem =  tbOrderItemList.get(i);
            tbOrderItem.setId(oderItemId.toString());
            tbOrderItem.setOrderId(String.valueOf(orderId));
            tbOrderItemMapper.insertSelective(tbOrderItem);
        }

        //tbordershiping
        tbOrderShipping.setOrderId(String.valueOf(orderId));
        tbOrderShipping.setCreated(new Date());
        tbOrderShipping.setUpdated(new Date());
        tbOrderShippingMapper.insertSelective(tbOrderShipping);


        //分布式事务扣减库存存 本地消息记录表
        LocalMessage localMessage=new LocalMessage();
        localMessage.setTxNo(UUID.randomUUID().toString());
        localMessage.setOrderNo(String.valueOf(orderId));
        localMessage.setState(0);
        localMessageMapper.insertSelective(localMessage);

        mqSender.sendMsg(localMessage);



        //发消息扣减库存
        //amqpTemplate.convertAndSend("order_exchage","order.add",orderId);

        return orderId;
    }
}
